const path = require('path')
const router = require('koa-router')()
const model = require('../../models/user')
const dao = require('../../dao/' + path.basename(__dirname))
const daoUser = require('../../dao/user')

// 用户注册

router.post('/', async function (ctx, next) {
    const body = ctx.request.body
    if (!body.name || !body.password || !body.email) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '缺少必须字段（用户名/密码/邮箱）!'
        }
        return
    }

    if (body.name.length >= 16 || body.name.length <= 0) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '用户名太长或太短!'
        }
        return
    }

    if (!/^[a-zA-Z0-9]{8,15}$/.test(body.password)) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '密码格式不正确!'
        }
        return
    }

    if (!/^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,5})$/.test(body.email)) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '邮箱格式不正确!'
        }
        return
    }

    if (body.student_id && !/(^\d{9,11}$)/.test(body.student_id)) {
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '学号格式不正确!'
        }
        return
    }

    const name_user = await model.findOne({
        where: {
            username: body.name,
        }
    });
    if (name_user) {
        console.log('已存在同名用户!');
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '已存在同名用户!'
        }
        return
    }

    const email_user = await model.findOne({
        where: {
            email: body.email,
        }
    });
    if (email_user) {
        console.log('该邮箱已注册!');
        ctx.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '该邮箱已注册!'
        }
        return
    }

    const user = {
        username: body.name,
        password: body.password,
        student_id: body.student_id,
        email: body.email,
    }
    const entity = await model.create(user)
    ctx.status = 200;
    ctx.type = 'json/application';
    ctx.response.body = {
        code: 200,
        user: entity,
    }

    await next();
});

module.exports = router.routes();